<?php
/*
 * @Author: 1086 cchcc@qq.com
 * @Date: 2024-04-22 10:38:36
 * @LastEditors: 1086 cchcc@qq.com
 * @LastEditTime: 2024-05-19 10:20:40
 * @FilePath: \erp\api\php\app\pos_v1\controller\SellPos.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
/*
 * @Author: 1086 cchcc@qq.com
 * @Date: 2024-04-22 10:38:36
 * @LastEditors: 1086 cchcc@qq.com
 * @LastEditTime: 2024-05-14 10:02:26
 * @FilePath: \erp\api\php\app\pos_v1\controller\SellPos.php
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
declare(strict_types=1);
namespace app\pos_v1\controller;

use think\facade\Db; //门面模式
use app\pos_v1\model\SellPos as mysql; //导入模型
// POS销售单据
class SellPos
{

    // HTTP请求
    function curl_HTTP($url, $header, $pos_db)
    {
        return false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);  // 从证书中检查SSL加密算法是否存在
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, 0); //如果想把一个头包含在输出中，设置这个选项为一个非零值。
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果成功只将结果返回，不自动输出任何内容。
        curl_setopt($ch, CURLOPT_POST, 1); //设置为POST方式
        curl_setopt($ch, CURLOPT_POSTFIELDS, $pos_db); //POST数据
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 0);
        curl_setopt($ch, CURLINFO_HEADER_OUT, 1); //启用时追踪句柄的请求字符串。
        $response = curl_exec($ch);
        //dump(curl_error($ch));  //查看报错信息
        // 写文件
        // file_put_contents("ajs/web_api_" . date("Y-m-d_H-i-s", time()) . ".json", $response . "\n", FILE_APPEND);
        curl_close($ch);
        return $response;
    }

    // POS销售-预下单
    public function NewDbid()
    {
        $query = request()->param(); //请求参数
        //验证规则
        $vali_db = [
            "operator" => $query["operator"], //门店操作员
        ];
        $validate = new \app\pos_v1\validate\SellPos_NewDbid; //验证规则
        if (!$validate->check($vali_db)) {
            // 验证不过关提示
            $apidb = [
                "code" => 201, //状态码
                "msg" => "请求参数有误-" . $validate->getError(),
                "requestdb" => $query,
                "validate" => $validate->getError(),
            ];
            return json($apidb);
        }
        $dbid = "91" . date("ymdHis", time()) . rand(1000, 9999); //订单：前缀+2位年月日时分秒+四位随机数。例： "dbid": "9231114190243"
        // 订单表头写入
        $sqldb = mysql::create(
            [
                "dbid" => $dbid, //数据编号.唯一(系统单号)
                "state" => "C", //单据状态_A挂单B结算C空单
                "operator" => $query["operator"] ? $query["operator"] : "门店操作员", //门店操作员
                "sign" => base64_encode(md5("sign" . $dbid)), //改单签名串
            ]
        );
        if ($sqldb) {
            $code = 200;
            $msg = "生成下一笔销售单号-成功";
            $data_now = $sqldb->toArray();
        } else {
            $code = 201;
            $msg = "生成下一笔销售单号-失败";
            $data_now = [];
        }
        // API信息
        $help = [
            "code" => "错误代码",
            "time" => "接口运行时间",
            "msg" => "状态信息",
            "query=接口请求参数包" => [
                "operator" => "门店操作员"
            ],
            "db=接口回调核心数据包" => [
                "state" => "单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)E已整单退货",
                "dbid" => "单号",
                "sign" => "改单签名串",
                "operator" => "门店操作员"
            ]
        ];
        $apidb = [
            "code" => $code, //状态码
            "time" => time(), //
            "msg" => $msg, //状态信息
            // "query" => $query,
            "db" => $data_now,
            // "接口信息" => ["name" => "预下单", "notice" => "部分字段可能不返回，没用到的字段不要预设，部分描述文字可能有错误。", "help" => $help], //API信息
        ];
        return (json($apidb));
    }

    // POS销售-保存销售单
    public function PosOrderSave()
    {
        $query = request()->param(); //请求参数
        // 调用控制器模块
        $PosOrder = new \app\pos_v1\controller\classPosOrder;
        $db = $PosOrder->posorder($query);
        return (json($db));
    }

    // POS销售-前端当前操作的销售单
    public function PosOrderId()
    {
        $query = request()->param(); //请求参数
        // 查单头
        $order_db = mysql::where(["dbid" => $query["dbid"]])->find();
        if ($order_db == null) {
            return (json(["code" => 201, "time" => time(), "msg" => "订单不存在[111]", "query" => $query]));
        }

        //设置需要输出的属性
        $order_db->visible([

        ]);
        // 设置需要隐藏的输出属性
        $order_db->hidden([
            //     "id", //主键
        ]);
        // 设置需要附加的输出属性
        $order_db->append([
            // "goods_li", //附加字段-单据明细
        ]);
        // POS销售单据关联商品
        $goods_li = Db::table("pos__p_sell_order_detail")->where(["order_dbid" => $order_db["dbid"]])->select();


        // 支付流水表_总在帐金额
        $pay_net_amount = Db::table("pos__p_sell_order_pay")->where(["order_dbid" => $query["dbid"]])->column("net_amount");
        $pay_net_amount = array_sum($pay_net_amount);//对数组中所有值求和

        // API信息
        $help = [
            "code" => "错误代码",
            "time" => "接口运行时间",
            "msg" => "状态信息",
            "query=接口请求参数包" => [
                "dbid" => "要获取销售单单号"
            ],
            "db=接口回调核心数据包" => [
                "state" => "单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)E已整单退货",
                "dbid" => "数据编号.唯一(系统单号)",
                "sign" => "改单签名串",
                "type" => "单据类型_A1销售B1退货",
                "detail_length_query" => "明细请求长度",
                "detail_length_insert" => "明细写入长度",
                "operator" => "门店操作员",
                "total_price" => "整单总价",
                "total_discount" => "整单折扣",
                "tm_code" => "终端机器码",
                "tm_id" => "机器号",
                "time_new" => "计算属性-创建时间",
                "time_up" => "计算属性-修改时间",
                "remark" => "单据备注",
                "goods_db=商品数据数组包" =>
                    [
                        "barcode" => "条码",
                        "goods_dbid" => "商品数据编号",
                        "goods_name" => "商品名称",
                        "in_code" => "录入码",
                        "number" => "数量",
                        "order_dbid" => "对应订单数据编号",
                        "prc_sale_actual_sum" => "实际-零售价-小计",
                        "prc_sale_actual" => "实际-零售价",
                        "prc_sale" => "档案-零售价（原零售价）",
                        "remark" => "单行备注",
                        "unit_pack" => "是否大单位_A是B否",
                        "unit" => "单位",
                    ]
            ]
        ];
        // 原始价与实收价的差=整单总价_原始价-整单总价_实收价
        $price_reduce_difference = (float) bcsub((string) $order_db["total_price"], (string) $order_db["total_price_new"], 4);


        $pay_db = [

            "price_reduce" => $order_db["price_reduce"],//金额减免原因
            "price_reduce_val" => $order_db["price_reduce_val"],//减免金额
            "price_reduce_difference" => $price_reduce_difference,//原始价与实收价的差
            "total_discount" => $order_db["total_discount"],//整单折扣

            "total_price" => $order_db["total_price"],//整单总价_原始价
            "total_price_new" => $order_db["total_price_new"],//整单总价_实收价

            "total_price_new_received" => $pay_net_amount,//整单总价_实收价_的_已收款
            "total_price_new_pendingPayment" => (float) bcsub((string) $order_db["total_price_new"], (string) $pay_net_amount, 4),//[整单总价_实收价_的_待收款]=[整单总价_实收价] - [支付流水表_总在帐金额]
        ];


        $apidb = [
            "code" => 200,
            "time" => time(),
            "msg" => "获取当前操作的销售单-成功",
            "db" => $order_db,
            "goods_li" => $goods_li,
            "pay_db" => $pay_db,
            // "query" => $query,
            // "接口信息" => ["name" => "获取销售单", "notice" => "部分字段可能不返回，没用到的字段不要预设，部分描述文字可能有错误。", "help" => $help], //API信息
        ];
        return (json($apidb));
    }

    //POS销售-前端当前操作的销售单_减免金额操作
    public function PosOrderPriceReduce()
    {
        $query = request()->param(); //请求参数
        // 查单头
        $sqldb = mysql::where(["dbid" => $query["dbid"], "sign" => $query["sign"],])->find();
        // 查询返回空
        if ($sqldb == null) {
            return (json(["code" => 201, "msg" => "订单不存在",]));
        }
        // 单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
        if ($sqldb["state"] == "B") {
            return (json(["code" => 201, "msg" => "已结算单据,不能继续操作",]));
        }
        // 单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
        if ($sqldb["state"] == "F") {
            return (json(["code" => 201, "msg" => "已退货单据,不能继续操作",]));
        }


        //新的[整单总价_实收价]=[整单总价_原始价]-[减免金额]
        $total_price_new2 = (float) bcsub((string) $sqldb["total_price"], (string) $query["price_reduce_val"], 4);
        if ($total_price_new2 < 0) {
            $total_price_new = 0;
        } else {
            $total_price_new = $total_price_new2;
        }
        //更新:新的[整单总价_实收价][金额减免原因][减免金额]
        $update = Db::name("pos__p_sell_order")->where(["dbid" => $query["dbid"], "sign" => $query["sign"],])
            ->update([
                "total_price_new" => $total_price_new, //整单总价_实收价
                "price_reduce_val" => (float) $query["price_reduce_val"], //减免金额
                "price_reduce" => $query["price_reduce"], //金额减免原因
                "time_up" => time(), //计算属性-修改时间
            ]);
        if ($update) {

            //更新:新的[整单折扣]
            $sqldb2 = mysql::where(["dbid" => $query["dbid"], "sign" => $query["sign"],])->find();

            //[整单折扣]=[整单总价_实收价]/[整单总价_原始价]
            $total_discount = bcdiv((string) $sqldb2["total_price_new"], (string) $sqldb2["total_price"], 4);

            $sqldb2->total_discount = $total_discount; //整单折扣
            $sqldb2->time_up = time(); //计算属性-修改时间
            $sqldb2->save();
        } else {
            // $code = 201; //状态码
            // $msg = "审核-失败"; //状态信息
        }
        $apidb = [
            "code" => 200,
            "time" => time(),
            "msg" => "金额减免修改成功",
            "query" => $query,
            // "update" => $update,
            // "total_price_new" => $total_price_new,
            // "total_price_new2" => $total_price_new2,
            // "db" => $sqldb,
        ];
        return (json($apidb));
    }

    // 前台-历史单-列表
    public function PastOrderList()
    {
        $query = request()->param(); //请求参数

        $help = [
            "db" => [
                "total" => "数据总行数",
                "per_page" => "每页数量",
                "current_page" => "当前页码",
                "last_page" => "最后一页/总页数",
                "data" => "数据集",
            ]
        ];
        $Past_Order_List_dataSource = mysql::where([
            // ["cls_id", "IN", [1, 150, 129, 128, 123, 124, 154, 120, 121, 122]],
            // ["state", "=", "B"], //单据状态_A草稿B审核C作废
        ])
            ->order("id", "DESC")//搜索排序方式ASE,DESC升降序
            ->paginate([
                //[文档]https://www.kancloud.cn/manual/thinkphp6_0/1037638
                "list_rows" => $query["list_rows"] ?? 10, // 每页数量
                "page" => $query["page"] ?? 1, // 当前页
            ]);


        //设置需要输出的属性
        $Past_Order_List_dataSource->visible([
            "id",
            "state",//单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
            "dbid",//数据编号.唯一(系统单号)
            // "sign",//改单签名串
            "type",//单据类型_A1销售B1退货
            "detail_length_query",//明细请求长度
            "detail_length_insert",//明细写入长度
            "operator",//门店操作员
            "total_price",//整单总价
            "total_price_new",//整单总价新的实际的
            "total_discount",//整单折扣
            "time_new",//计算属性-创建时间
            "time_up",//计算属性-修改时间
            "remark",//单据备注
        ]);
        // 设置需要附加的输出属性
        $Past_Order_List_dataSource->append([
            // "state_mp",
            // "time_new_mp",
            // "time_up_mp",
        ]);
        // 设置数据字段获取器
        // 单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
        $Past_Order_List_dataSource->withAttr("state", function ($value, $data) {
            $res = ["A" => "挂单", "B" => "已结算", "C" => "预下单", "D" => "草稿单", "E" => "支付中", "F" => "已整单退货", null => null, "" => ""];
            return $res[$data["state"]];
        });
        // "type",//单据类型_A1销售B1退货
        $Past_Order_List_dataSource->withAttr("type", function ($value, $data) {
            $res = ["A1" => "销售", "B1" => "退货", null => null, "" => ""];
            return $res[$data["type"]];
        });
        // 创建时间
        $Past_Order_List_dataSource->withAttr("time_new", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_new"]);
        });
        // 修改时间
        $Past_Order_List_dataSource->withAttr("time_up", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_up"]);
        });

        // 历史单窗口-列表-表格字段
        $Past_Order_List_columns = [
            [
                "title" => "序号",
                "type" => "number",
                "align" => "center",
            ],
            // [
            //     "title" => "ID",
            //     "key" => "id",
            //     "sort" => "desc",
            //     "width" => "70px",
            //     "align" => "center",
            // ],
            [
                "title" => "单号",
                "key" => "dbid",
                "align" => "center",
            ],
            [
                "title" => "状态",
                "key" => "state",
                "sort" => "desc",
                "width" => "120px",
                "align" => "center",
            ],
            [
                "title" => "类型",
                "key" => "type",
                "sort" => "desc",
                "width" => "180px",
                "align" => "center",
            ],
            [
                "title" => "原始总价",//整单总价
                "key" => "total_price",
                "align" => "center",
            ],
            [
                "title" => "实际总价",//整单总价新的实际的
                "key" => "total_price_new",
                "width" => "200px",
                "align" => "center",
            ],
            [
                "title" => "折扣率",
                "key" => "total_discount",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "操作员",
                "width" => "70px",
                "key" => "operator",
                "align" => "center",
            ],
            // [
            //     "title" => "明细请求长度",
            //     "key" => "detail_length_query",
            //     "width" => "100px",
            //     "align" => "center",
            // ],
            [
                "title" => "商品",//明细写入长度
                "key" => "detail_length_insert",
                "width" => "60px",
                "align" => "center",
            ],


            [
                "title" => "创建时间",
                "key" => "time_new",
                "align" => "center",
            ],
            [
                "title" => "单据备注",
                "key" => "remark",
                "align" => "center",
                "ellipsisTooltip" => "true",
            ]


        ];


        $apidb = [
            "code" => 200,
            "time" => time(),
            "msg" => "获取历史销售单列表",
            "Past_Order_List_columns" => $Past_Order_List_columns,//前端表格字段
            "Past_Order_List_dataSource" => $Past_Order_List_dataSource,
            "query" => $query,
            "api" => ["name" => "获取历史销售单-列表", "help" => $help],


        ];
        return (json($apidb));
    }

    // 前台-历史单-一条单据信息
    public function PastOrderId()
    {
        // API信息
        $help = [
            "code" => "错误代码",
            "time" => "接口运行时间",
            "msg" => "状态信息",
            "query=接口请求参数包" => [
                "dbid" => "要获取销售单单号"
            ],
            "db=接口回调核心数据包" => [
                "state" => "单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)E已整单退货",
                "dbid" => "数据编号.唯一(系统单号)",
                "sign" => "改单签名串",
                "type" => "单据类型_A1销售B1退货",
                "detail_length_query" => "明细请求长度",
                "detail_length_insert" => "明细写入长度",
                "operator" => "门店操作员",
                "total_price" => "整单总价",
                "total_discount" => "整单折扣",
                "tm_code" => "终端机器码",
                "tm_id" => "机器号",
                "time_new" => "计算属性-创建时间",
                "time_up" => "计算属性-修改时间",
                "remark" => "单据备注",
                "goods_db=商品数据数组包" =>
                    [
                        "barcode" => "条码",
                        "goods_dbid" => "商品数据编号",
                        "goods_name" => "商品名称",
                        "in_code" => "录入码",
                        "number" => "数量",
                        "order_dbid" => "对应订单数据编号",
                        "prc_sale_actual_sum" => "实际-零售价-小计",
                        "prc_sale_actual" => "实际-零售价",
                        "prc_sale" => "档案-零售价（原零售价）",
                        "remark" => "单行备注",
                        "unit_pack" => "是否大单位_A是B否",
                        "unit" => "单位",
                    ]
            ]
        ];

        $query = request()->param(); //请求参数
        // 查单头 
        $order_sql_db = mysql::where(["dbid" => $query["dbid"]])->find();
        if ($order_sql_db == null) {
            return (json(["code" => 201, "time" => time(), "msg" => "订单不存在[294]", "query" => $query]));
        }
        // 设置需要附加的输出属性
        $order_sql_db->append([
            "state_mp",
            "type_mp",
            "time_new_mp",
            "time_up_mp",
        ]);

        // 设置数据字段获取器
        // 单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
        $order_sql_db->withAttr("state_mp", function ($value, $data) {
            $res = ["A" => "挂单", "B" => "已结算", "C" => "预下单", "D" => "草稿单", "E" => "支付中", "F" => "已整单退货"];
            return $res[$data["state"]];
        });
        // 单据类型_A1销售B1退货
        $order_sql_db->withAttr("type_mp", function ($value, $data) {
            $res = ["A1" => "销售", "B1" => "退货", null => "null", "" => ""];
            return $res[$data["type"]];
        });
        // 创建时间
        $order_sql_db->withAttr("time_new_mp", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_new"]);
        });
        // 修改时间
        $order_sql_db->withAttr("time_up_mp", function ($value, $data) {
            return date("Y-m-d H:i:s", $data["time_up"]);
        });

        // 选项卡-单头字段别名
        $order_db_alias = [
            "id" => "主键编号",
            "state" => "单据状态",//单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
            "dbid" => "单据编号",//数据编号.唯一(系统单号)
            "sign" => "改单签名串",//改单签名串
            "type" => "单据类型",//单据类型_A1销售B1退货
            "detail_length_query" => "明细请求长度",//明细请求长度
            "detail_length_insert" => "明细写入长度",//明细写入长度
            "operator" => "操作员工",//门店操作员
            "total_price" => "整单总价原来",//整单总价
            "total_price_new" => "整单总价实际",//整单总价新的实际的
            "total_discount" => "整单折扣",//整单折扣
            "tm_code" => "终端机器码",//终端机器码
            "tm_id" => "机器号",//机器号
            "time_new" => "创建时间",//计算属性-创建时间
            "time_up" => "修改时间",//计算属性-修改时间
            "remark" => "单据备注",//单据备注
        ];

        // 选项卡-单头信息
        $order_db = [
            "id" => $order_sql_db["id"],
            "state" => $order_sql_db["state"],//单据状态_A挂单B已结算(锁定)C预下单号D草稿单E支付中(锁定)F已整单退货
            "dbid" => $order_sql_db["dbid"],//数据编号.唯一(系统单号)
            "sign" => $order_sql_db["sign"],//改单签名串
            "type" => $order_sql_db["type"],//单据类型_A1销售B1退货
            "detail_length_query" => $order_sql_db["detail_length_query"],//明细请求长度
            "detail_length_insert" => $order_sql_db["detail_length_insert"],//明细写入长度
            "operator" => $order_sql_db["operator"],//门店操作员
            "total_price" => $order_sql_db["total_price"],//整单总价
            "total_price_new" => $order_sql_db["total_price_new"],//整单总价新的实际的
            "total_discount" => $order_sql_db["total_discount"],//整单折扣
            "tm_code" => $order_sql_db["tm_code"],//终端机器码
            "tm_id" => $order_sql_db["tm_id"],//机器号
            "time_new" => $order_sql_db["time_new"],//计算属性-创建时间
            "time_up" => $order_sql_db["time_up"],//计算属性-修改时间
            "remark" => $order_sql_db["remark"],//单据备注

            "state_mp" => $order_sql_db["state_mp"],//单据状态
            "type_mp" => $order_sql_db["type_mp"],//单据类型
            "time_new_mp" => $order_sql_db["time_new_mp"],//创建时间
            "time_up_mp" => $order_sql_db["time_up_mp"],//修改时间
        ];


        // POS销售单据关联商品
        // 选项卡-商品信息-表格数据
        $past_order_goods_dataSource = Db::table("pos__p_sell_order_detail")->where(["order_dbid" => $order_sql_db["dbid"]])
            ->withoutField([
                // 隐藏的输出属性
                "remark",
            ])
            ->withAttr("unit_pack", function ($value, $data) {
                // 是否大单位_A是B否
                $res = ["A" => "是", "B" => "否", null => "null", "" => ""];
                return $res[$data["unit_pack"]];
            })
            ->select();
        // 选项卡-商品信息-表格字段
        $past_order_goods_columns = [
            [
                "title" => "序号",
                "type" => "number",
                "width" => "50px",
                "align" => "center",
            ],
            // [
            //     "title" => "ID",
            //     "key" => "id",
            //     "sort" => "desc",
            //     "width" => "54px",
            //     "align" => "center",
            // ],
            [
                "title" => "单号",
                "key" => "order_dbid",
                "width" => "142px",
                "align" => "center",
            ],
            [
                "title" => "条码",
                "key" => "barcode",
                "width" => "140px",
                "align" => "center",
            ],
            [
                "title" => "录入码",
                "key" => "in_code",
                "width" => "140px",
                "align" => "center",
            ],
            [
                "title" => "数据编号",//商品数据编号
                "key" => "goods_dbid",
                "width" => "140px",
                "align" => "center",
            ],
            [
                "title" => "商品名称",
                "key" => "goods_name",
                "width" => "140px",
                "align" => "center",
            ],
            [
                "title" => "数量",
                "key" => "number",
                "width" => "50px",
                "align" => "center",
            ],
            [
                "title" => "档案零价",
                "key" => "prc_sale",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "实际零价",
                "key" => "prc_sale_actual",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "实际零价小计",
                "key" => "prc_sale_actual_sum",
                "width" => "100px",
                "align" => "center",
            ],
            [
                "title" => "单位",
                "key" => "unit",
                "width" => "50px",
                "align" => "center",
            ],
            [
                "title" => "大单位",//是否大单位_A是B否
                "key" => "unit_pack",
                "width" => "60px",
                "align" => "center",
            ],
            [
                "title" => "备注",
                "key" => "remark",
                "align" => "center",
            ],

        ];

        // POS销售单据关联支付信息
        // 选项卡-支付信息-表格数据
        $past_order_pay_dataSource = Db::table("pos__p_sell_order_pay")->where(["order_dbid" => $order_sql_db["dbid"]])
            ->field([
                // 标识要返回的字段
                "id",
                "order_dbid",//销售单号
                "client_sn",//流水单号
                "pay_sn",//支付系统单号
                "payway",//支付方式_9现金8线上支付
                "state",//单据状态_ES异常状态A支付成功B1全额退款B2部分退款B3退款进行中
                "pay_currency",//支付币种-A1其它现金_B1其它电子支付-RMB人民币HKD港币USD美元_WXPAY微信ZFBPAY支付宝BDPAY百度钱包JDPAY京东钱包QQPAY_QQ钱包
                "pay_currency_name",//支付币种_名称
                "pay_currency_ico",//支付币种_图标
                "total_amount",//原始交易实收金额
                "net_amount",//实收金额减退款金额
                "time_new",//创建时间
                "time_up",//更新时间
                "x_del",//预删除1是0否
                "exchange_rate",//汇率
            ])
            ->withAttr("time_new", function ($value, $data) {
                return date("Y-m-d H:i:s", $value);
            })
            ->withAttr("time_up", function ($value, $data) {
                return date("Y-m-d H:i:s", $value);
            })
            ->withAttr("payway", function ($value, $data) {
                $res = ["A1" => "销售", "B1" => "退货", null => "null", "" => ""];
                return $res[$data["payway"]];
            })
            ->withAttr("payway", function ($value, $data) {
                // 支付方式_9现金8线上支付
                $res = ["9" => "现金支付", "8" => "线上支付", null => "null", "" => ""];
                return $res[$data["payway"]];
            })
            ->withAttr("state", function ($value, $data) {
                // 单据状态_ES异常状态A支付成功B1全额退款B2部分退款B3退款进行中
                $res = ["ES" => "异常", "A" => "支付成功", "B1" => "全额退款", "B2" => "部分退款", "B3" => "退款进行中", null => "null", "" => ""];
                return $res[$data["state"]];
            })
            ->withAttr("x_del", function ($value, $data) {
                // 预删除1是0否
                $res = ["1" => "是", "0" => "否", null => "null", "" => ""];
                return $res[$data["x_del"]];
            })
            ->select();


        // 选项卡-支付信息-表格字段
        $past_order_pay_columns = [
            [
                "title" => "序号",
                "type" => "number",
                "width" => "50px",
                "align" => "center",
            ],
            [
                "title" => "ID",
                "key" => "id",
                "sort" => "desc",
                "width" => "54px",
                "align" => "center",
            ],
            [
                "title" => "销售单号",
                "key" => "order_dbid",
                "width" => "142px",
                "align" => "center",
            ],
            [
                "title" => "流水单号",
                "key" => "client_sn",
                "width" => "142px",
                "align" => "center",
            ],
            [
                "title" => "支付单号",//支付系统单号
                "key" => "pay_sn",
                "width" => "142px",
                "align" => "center",
            ],
            [
                "title" => "支付方式",//支付方式_9现金8线上支付
                "key" => "payway",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "单据状态",//单据状态_ES异常状态A支付成功B1全额退款B2部分退款B3退款进行中
                "key" => "state",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "支付币种",//支付币种-A1其它现金_B1其它电子支付-RMB人民币HKD港币USD美元_WXPAY微信ZFBPAY支付宝BDPAY百度钱包JDPAY京东钱包QQPAY_QQ钱包
                "key" => "pay_currency",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "币种名称",
                "key" => "pay_currency_name",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "币种图标",
                "key" => "pay_currency_ico",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "原始金额",//原始交易实收金额
                "key" => "total_amount",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "在帐金额",//实收金额减退款金额
                "key" => "net_amount",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "汇率",
                "key" => "exchange_rate",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "预删除",//预删除1是0否
                "key" => "x_del",
                "width" => "70px",
                "align" => "center",
            ],
            [
                "title" => "创建时间",
                "key" => "time_new",
                "width" => "134px",
                "align" => "center",
            ],
            [
                "title" => "更新时间",
                "key" => "time_up",
                "width" => "134px",
                "align" => "center",
            ],

            // [
            //     "title" => "支付接口回调-查询回调",
            //     "key" => "pay_api_notify_query",
            //     "align" => "center",
            // ],
            // [
            //     "title" => "商家扫用户支付接口回调",
            //     "key" => "pay_db",
            //     "align" => "center",
            // ],

        ];


        $apidb = [
            "code" => 200,
            "time" => time(),
            "msg" => "获取历史销售单成功！",
            "order_db" => $order_db,// 选项卡-单头信息
            "order_db_alias" => $order_db_alias,// 选项卡-单头字段别名
            "past_order_goods_columns" => $past_order_goods_columns,// 选项卡-商品信息-表格字段
            "past_order_goods_dataSource" => $past_order_goods_dataSource,// 选项卡-商品信息-表格数据
            "past_order_pay_columns" => $past_order_pay_columns,// 选项卡-支付信息-表格字段
            "past_order_pay_dataSource" => $past_order_pay_dataSource,// 选项卡-支付信息-表格数据
            "query" => $query,
            "接口信息" => ["name" => "获取历史销售单", "notice" => "部分字段可能不返回，没用到的字段不要预设，部分描述文字可能有错误。", "help" => $help], //API信息
        ];
        return (json($apidb));
    }



    // 查询一条单据
    public function _id()
    {
        $query = request()->param(); //请求参数
        // 查单头
        if (isset($query["dbid"]) && $query["dbid"] != "") {
            $sqldb = mysql::where("dbid", "=", $query["dbid"])->find(); //精准查询
        } else {
            $sqldb = mysql::order("id", "desc")->find(); //空查返回最新一条数据
        }
        ;
        // 单据头部-成功-查明细
        if ($sqldb) {
            //设置需要输出的属性
            $sqldb = $sqldb->visible([
                //     "id", //主键
            ]);
            // 设置需要隐藏的输出属性
            $sqldb = $sqldb->hidden([
                //     "id", //主键
            ]);
            // 设置需要附加的输出属性
            $sqldb = $sqldb->append([
                "table_detail", //附加字段-单据明细
            ]);
            // 设置数据字段获取器
            $sqldb = $sqldb->withAttr("db_state", function ($value, $data) {
                $res = ["A" => "删除", "B" => "停用", "C" => "只销"];
                return ["val" => $value, "mp" => $res[$value], "txt" => "商品状态"];
            });
            $sqldb = $sqldb->withAttr("unit_pack", function ($value, $data) {
                $res = ["A" => "是", "B" => "否"];
                return ["val" => $value, "mp" => $res[$value], "txt" => "是否大单位"];
            });
            $sqldb = $sqldb->withAttr("time_new", function ($value, $data) {
                return ["val" => $value, "mp" => date("Y-m-d H:i:s", $value), "txt" => "创建时间"];
            });
            $sqldb = $sqldb->withAttr("time_up", function ($value, $data) {
                return ["val" => $value, "mp" => date("Y-m-d H:i:s", $value), "txt" => "修改时间"];
            });
            // 查单头成功查单据明细
            $sql_table_detail = Db::table("pos__p_sell_order_detail")
                ->where("order_dbid", "=", $sqldb["dbid"])
                ->order("id", "desc")
                ->withAttr("unit_pack", function ($value, $data) {
                    // 设置数据字段获取器
                    $res = ["A" => "是", "B" => "否"];
                    return ["val" => $value, "mp" => $res[$value], "txt" => "是否大单位"];
                })
                ->select()
                ->toArray();
            if ($sql_table_detail) {
                $code = 200;
                $msg = "查询明细-成功";
                $sqldb["table_detail"] = $sql_table_detail;
            } else {
                $code = 200;
                $msg = "查询明细-成功-0条";
                $sqldb["table_detail"] = [];
            }
            $sqldb->detail_length_insert = count($sql_table_detail); //明细写入长度
            $sqldb->save();
        } else {
            $code = 201;
            $msg = "单据不存在";
            $sqldb["table_detail"] = [];
        }
        $apidb = [
            "code" => $code, //状态码
            "msg" => $msg, //状态信息
            "query" => $query, //请求参数
            "data" => $sqldb,
        ];
        return (json($apidb));
    }

    // 列表
    public function _List()
    {
        $query = request()->param(); //请求参数
        $limit = request()->param("limit", 10, "trim"); //每页行数
        $current = request()->param("current", 1, "trim"); //页码
        if ($query["additional"]["use"] == 1) {
            // additional.use启用额外查询方法-0否-1是。
            $SearchField = $query["additional"]["SearchField"]; //搜索字段
            $SearchOperator = $query["additional"]["SearchOperator"]; //搜索查询表达式
            $SearchaAtistop = $query["additional"]["SearchaAtistop"]; //搜索关键词SearchaAtistop:"[4,28,29,30,31,32,33,34]"
        } else {
            $SearchField = request()->param("SearchField", "id", "trim"); //搜索字段
            $SearchOperator = request()->param("SearchOperator", "LIKE", "trim"); //搜索查询表达式
            $SearchaAtistop = strval(request()->param("SearchaAtistop", "", "trim")); //搜索关键词
        }
        $SearchaSort = request()->param("SearchaSort", "DESC", "trim"); //搜索排序方式ASE,DESC升降序
        $SearchaSortField = request()->param("SearchaSortField", "id", "trim"); //排序字段
        // 查询表达式
        if ($SearchOperator == "LIKE") {
            $SearchaAtistop = "%" . $SearchaAtistop . "%";
        }
        ;
        if ($SearchField == "time_new" || $SearchField == "time_up") {
            if ($SearchOperator == ">" || $SearchOperator == "<") {
                $SearchaAtistop = strtotime(strval($SearchaAtistop));
                if ($SearchField == "time_new") {
                    $SearchField = "time_new";
                } else if ($SearchField == "time_up") {
                    $SearchField = "time_up";
                }
            }
        }
        $help = [
            "db" => [
                "total" => "数据总行数",
                "per_page" => "每页数量",
                "current_page" => "当前页码",
                "last_page" => "最后一页/总页数",
                "data" => "数据集",
                "SearchaAtistop" => $SearchaAtistop
            ]
        ];
        $sqldb = mysql::where([
            [$SearchField, $SearchOperator, $SearchaAtistop],
            // ["cls_id", "IN", [1, 150, 129, 128, 123, 124, 154, 120, 121, 122]],
            // ["state", "=", "B"], //单据状态_A草稿B审核C作废
        ])
            ->order($SearchaSortField, $SearchaSort)
            ->paginate([ //[文档]https://www.kancloud.cn/manual/thinkphp6_0/1037638
                "list_rows" => $limit, // 每页数量
                "page" => $current, // 当前页
                // "query" => $query,//url额外参数
            ]);
        // 设置数据字段获取器
        //   单据类型_A1采购入库B1采购退货C1赠品入库D1报损出库
        $sqldb = $sqldb->withAttr("type", function ($value, $data) {
            $res = ["A1" => "采购入库", "B1" => "采购退货", "C1" => "赠品入库", "D1" => "报损出库"];
            return ["val" => $value, "mp" => $res[$value], "txt" => "单据类型"];
        });
        // 单据状态_A草稿B审核C作废
        $sqldb = $sqldb->withAttr("state", function ($value, $data) {
            $res = ["A" => "草稿", "B" => "审核", "C" => "作废"];
            return ["val" => $value, "mp" => $res[$value], "txt" => "单据状态"];
        });
        $sqldb = $sqldb->withAttr("time_new", function ($value, $data) {
            return ["val" => $value, "mp" => date("Y-m-d H:i:s", $value), "txt" => "创建时间"];
        });
        $sqldb = $sqldb->withAttr("time_up", function ($value, $data) {
            return ["val" => $value, "mp" => date("Y-m-d H:i:s", $value), "txt" => "修改时间"];
        });
        $sqldb2 = $sqldb->toArray();
        //  当前页起始行
        if ($current > 1) {
            $index2 = $limit * $current - $limit + 1;
        } else {
            $index2 = 1;
        }
        // echo "当前总下标：" . $index2;
        for ($x = 0; $x < count($sqldb); $x++) {
            $sqldb2["data"][$x]["index1"] = $x + 1;
            $sqldb2["data"][$x]["index2"] = $index2;
            $index2++;
            $reset = null;
            // $reset = Db::table("admin__i_goods_cls")->where("id", $sqldb2["data"][$x]["cls_id"])->find();
            // $sqldb2["data"][$x]["cls_name"] = !empty($reset["name"]) ? $reset["name"] : "!断链分类" . $sqldb2["data"][$x]["cls_id"];
        }
        $apidb = [
            "api" => ["name" => "采购单据列表", "help" => $help], //API信息
            "code" => 200, //状态码
            "msg" => "查询成功！", //状态信息
            "query" => $query, //请求参数
            "data" => $sqldb2,
        ];
        return (json($apidb));
    }

    // 审核-写库存
    public function _Finish()
    {
        $query = request()->param(); //请求参数
        $time_int = time();
        $time = date("Y-m-d H:i:s", $time_int);
        // 查单头
        $sqldb = mysql::where([
            ["dbid", "=", $query["table_header"]["dbid"]],
            // ["state", "=", "A"], //单据状态_A草稿B审核C作废
        ])->findOrEmpty();
        // 查询返回空
        if ($sqldb->isEmpty()) {
            $apidb = [
                "code" => 201, //状态码
                "msg" => "查询不到相关单据", //状态信息
                "query" => $query, //请求参数
                "data" => [],
            ];
            return (json($apidb));
        } else {
            // 单据状态_A草稿B审核C作废
            if ($sqldb["state"] != "A") {
                $apidb = [
                    "code" => 205, //状态码
                    "msg" => "此单据不能审核", //状态信息
                    "query" => $query, //请求参数
                    "data" => $sqldb,
                ];
                return (json($apidb));
            }
            ;
            // 获取-单据明细
            $sql_detail = Db::table("pos__p_sell_order_detail")->where("order_dbid", "=", $sqldb["dbid"])->select();
            if ($sql_detail) {
                // 遍历-单据明细
                foreach ($sql_detail as $item) {
                    // dump($item["goods_dbid"]); //商品数据编号
                    // dump($item["number"]); //数量
                    $detail_id = Db::table("admin__i_goods_stock")->where("goods_dbid", "=", $item["goods_dbid"])->find(); //查-库存信息
                    if ($detail_id) {
                        // 库存信息-存在-累加
                        $number = $detail_id["number"] + $item["number"];
                        //更新库存
                        $update = Db::name("admin__i_goods_stock")->where("goods_dbid", "=", $item["goods_dbid"])->update(["number" => $number]);
                        if ($update) {
                            // 更新库存-成功
                            $code = 200; //状态码
                            $msg = "审核成功"; //状态信息
                            $sqldb->time_up = $time_int; //修改时间
                            $sqldb->state = "B"; //单据状态_A草稿B审核C作废
                            $sqldb->save();
                        } else {
                            $code = 201; //状态码
                            $msg = "审核-失败"; //状态信息
                        }
                    } else {
                        // 库存信息-不存在-新增
                        $data = ["goods_dbid" => $item["goods_dbid"], "number" => $item["number"]];
                        $insert_id = Db::name("admin__i_goods_stock")->insert($data);
                        if ($insert_id) {
                            // 写入库存信息-成功
                            // dump($insert_id);
                            $code = 200; //状态码
                            $msg = "审核成功"; //状态信息
                            $sqldb->time_up = $time_int; //修改时间
                            $sqldb->state = "B"; //单据状态_A草稿B审核C作废
                            $sqldb->save();
                        } else {
                            $code = 202; //状态码
                            $msg = "审核-失败"; //状态信息
                        }
                    }
                }
            } else {
                $code = 203; //状态码
                $msg = "审核失败-单据明细没数据"; //状态信息
            }
        }
        $apidb = [
            "code" => $code, //状态码
            "msg" => $msg, //状态信息
            "query" => $query, //请求参数
            "data" => $sqldb,
        ];
        return (json($apidb));
    }
}
